<template>
	<main-content
		:tableHeight.sync="tableHeight"
		:otherDependenComponents="otherDependenComponents"
	>
		<template slot="query">
			<el-form
				ref="ruleForm"
				:model="ruleForm"
				label-width="120px"
				class="rule-form"
				:inline="true"
			>
				<!-- 功能开关 -->
				<SwitchToggle
					permissionId="90240047"
					:configData="configData"
					:key="switchKey"
					@getTypeValueAddedConfig="getValueAddedConfigByType"
				></SwitchToggle>
				<el-form-item
					:label="$t('dxn.service_manager.send_message_interval')"
				>
					<el-input
						v-if="isEdit"
						v-model="ruleForm.sendMessageInterval"
						style="width: 80px;"
						v-input="{ name: 'int' }"
						:maxlength="2"
					></el-input>
					<span v-else>
						{{ ruleForm.sendMessageInterval }}
					</span>
					<span>秒</span>
				</el-form-item>

				<el-form-item
					v-if="hasPermission('90240047')"
					style="margin-left: 20px;"
				>
					<div v-if="!isEdit">
						<el-button
							type="primary"
							@click="handleConfigEdit"
							size="small"
						>
							{{ $t('dxn.game_rule.edit_btn') }}
						</el-button>
					</div>
					<div v-else>
						<el-button
							type="plain"
							@click="handleConfigCancel"
							size="small"
						>
							{{ $t('dxn.game_rule.cancel_btn') }}
						</el-button>
						<el-button
							type="primary"
							:loading="btnLoading"
							@click="handleConfigSubmit"
							size="small"
						>
							{{ $t('dxn.game_rule.save_btn') }}
						</el-button>
					</div>
				</el-form-item>
			</el-form>
			<div class="show-add-btn">
				<el-button
					v-if="hasPermission('90240048')"
					type="primary"
					@click="showEditForm"
					:disabled="loading"
					size="small"
				>
					{{ $t('common.add') }}
				</el-button>
				<el-button
					v-if="hasPermission('90750073')"
					type="warning"
					icon="el-icon-download"
					size="small"
					:loading="exportBtnLoading"
					:disabled="loading"
					@click="exportExcel"
				>
					{{ $t('dxn.card_ables_list.export_excel') }}
				</el-button>
			</div>
		</template>
		<template slot="content">
			<el-table
				v-loading="loading"
				element-loading-spinner="el-icon-loading"
				border
				size="mini"
				class="small-size-table"
				:data="dataList"
				style="width: 100%;"
				:max-height="tableHeight"
				highlight-current-row
				header-align="center"
				:header-cell-style="getRowClass"
			>
				<el-table-column
					align="center"
					:label="$t('dxn.service_manager.sort')"
					min-width="100"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.sort + '' || '-' }}
					</template>
				</el-table-column>

				<el-table-column
					align="center"
					:label="$t('dxn.service_manager.barrage_content')"
					min-width="350"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.content || '-' }}
					</template>
				</el-table-column>

				<el-table-column
					align="center"
					:label="$t('common.last_updateBy')"
					min-width="120"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.updatedBy || '-' }}
					</template>
				</el-table-column>

				<el-table-column
					align="center"
					:label="$t('common.createAt')"
					min-width="200"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.createAt || '-' }}
					</template>
				</el-table-column>

				<el-table-column
					align="center"
					:label="$t('common.last_updateAt')"
					min-width="200"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.updateAt || '-' }}
					</template>
				</el-table-column>

				<el-table-column
					align="center"
					:label="$t('common.status')"
					min-width="100"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<span
							v-if="scope.row.state === '0'"
							class="disable-color"
						>
							{{ $t('common.status_disabled') }}
						</span>
						<span v-else-if="scope.row.state === '1'">
							{{ $t('common.components.oning') }}
						</span>
						<span v-else>-</span>
					</template>
				</el-table-column>

				<el-table-column
					align="center"
					:label="$t('common.actions')"
					min-width="200"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<div class="show-action-btn">
							<template v-if="hasPermission('90240051')">
								<span
									v-if="scope.row.state === '1'"
									class="text-disable"
									@click="updateRowStatus(scope.row, 0)"
								>
									{{ $t('common.disabled') }}
								</span>
								<span
									v-else
									class="text-start-up"
									@click="updateRowStatus(scope.row, 1)"
								>
									{{ $t('common.start_up') }}
								</span>
							</template>
							<span
								v-if="hasPermission('90240050')"
								class="text-delete"
								@click="deleteRow(scope.row)"
							>
								{{ $t('common.delete') }}
							</span>
							<span
								v-if="hasPermission('90240049')"
								class="text-edit"
								@click.stop="showEditForm(scope.row)"
							>
								{{ $t('common.edit') }}
							</span>
						</div>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				v-if="total"
				class="pageValue"
				background
				layout="total, sizes,prev, pager, next, jumper"
				:current-page.sync="pageNum"
				:page-size="pageSize"
				:page-sizes="pageSizes"
				:total="total"
				:pager-count="9"
				@current-change="handleCurrentChange"
				@size-change="handleSizeChange"
			/>
		</template>
		<el-dialog
			v-if="editVisible"
			:title="
				editForm.id
					? $t('common.edit')
					: $t('common.add') + $t('routes.dxn.chat_barrage')
			"
			:visible.sync="editVisible"
			:destroy-on-close="true"
			@close="cancelAddOrEdit"
			width="600px"
			center
		>
			<el-form
				ref="editForm"
				:model="editForm"
				label-width="100px"
				label-suffix=":"
			>
				<el-form-item
					prop="sort"
					:label="$t('dxn.service_manager.sort')"
					:rules="[
						{
							required: true,
							message: $t('common.please_enter'),
							trigger: 'blur'
						}
					]"
				>
					<el-input
						v-model="editForm.sort"
						autocomplete="off"
						style="width: 120px"
						v-input="{ name: 'int' }"
						:maxlength="3"
						:placeholder="$t('common.please_enter')"
						clearable
					></el-input>
				</el-form-item>
				<el-form-item
					prop="barrageContent"
					:label="$t('dxn.service_manager.barrage_content')"
					:rules="[
						{
							required: true,
							message: $t(
								'dxn.service_manager.barrage_content_tips'
							),
							trigger: 'blur'
						}
					]"
				>
					<el-input
						v-model="editForm.barrageContent"
						autocomplete="off"
						style="width:100%"
						v-input="{ name: 'noEmpty' }"
						:placeholder="
							$t('dxn.service_manager.barrage_content_tips')
						"
						:maxlength="40"
						clearable
						@input="handleBarrageContentInput"
					></el-input>
				</el-form-item>
				<div style="text-align:right;font-size:12px;">
					{{ $t('dxn.service_manager.barrage_content_limit') }}
				</div>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="cancelAddOrEdit">
					{{ $t('common.cancel') }}
				</el-button>
				<el-button
					type="primary"
					:loading="editLoading"
					:disabled="editLoading"
					@click="submitAddOrEdit"
				>
					{{ $t('common.save') }}
				</el-button>
			</div>
		</el-dialog>
	</main-content>
</template>

<script>
import list from '@/mixins/list'
import { routerNames } from '@/utils/consts'
import { getNewSubStrAndLen } from '@/utils/validate'
import SwitchToggle from '../components/SwitchToggle'
import MainContent from '@/components/MainContent/index.vue'
export default {
	name: routerNames.chatBarrage,
	components: { SwitchToggle, MainContent },
	mixins: [list],
	data() {
		return {
			tableHeight: 480,
			otherDependenComponents: [],
			pageSize: 100,
			dataList: [],
			loading: false,
			btnLoading: false,
			editLoading: false,
			isEdit: false,
			disabled: true,
			switchKey: 0,
			configType: 1,
			configItem: {},
			configData: {
				configId: 0,
				configStatus: 0
			},
			ruleForm: {
				sendMessageInterval: undefined
			},
			editTitle: '',
			editVisible: false,
			editForm: {
				id: undefined,
				sort: undefined,
				barrageContent: undefined
			},
			exportBtnLoading: false
		}
	},
	created() {
		this.getValueAddedConfigByType()
	},
	methods: {
		exportExcel() {
			const params = {}
			this.exportBtnLoading = true
			this.exportExcelPublic({
				api: 'exportChatBarrage',
				params
			}).finally(() => {
				this.exportBtnLoading = false
			})
		},
		getValueAddedConfigByType() {
			const params = { type: this.configType }
			this.$api.getValueAddedConfigByTypeBend(params).then((res) => {
				this.configItem = res?.data[0] || {}
				this.configData = {
					configId: this.configItem.id,
					configStatus: this.configItem.enableFlag || 0
				}
				this.ruleForm = {
					sendMessageInterval: this.configItem.sendMessageInterval
				}
				this.switchKey = Math.random()
			})
		},
		loadData() {
			this.loading = true
			this.dataList = []
			const params = this.getParams()
			this.$api
				.getChatPhrasesPageListBend(params)
				.then((res) => {
					this.loading = false
					if (res?.code === 200) {
						this.dataList = res?.data?.record
						this.total = res?.data?.totalRecord
					}
				})
				.catch(() => {
					this.loading = false
				})
		},
		submitAddOrEdit() {
			this.$refs.editForm.validate((valid) => {
				if (valid) {
					this.editLoading = true
					const params = {
						sort: this.editForm.sort,
						content: this.editForm.barrageContent
					}
					let apiPath = ''
					if (this.editForm?.id) {
						params.id = this.editForm?.id
						apiPath = 'updateChatPhrasesBend'
					} else {
						apiPath = 'addChatPhrasesBend'
					}
					this.$api[apiPath](params)
						.then((res) => {
							this.editLoading = false
							if (res?.code === 200) {
								this.editVisible = false
								this.$message.success(
									this.$t('common.action_success')
								)
								this.loadData()
							}
						})
						.catch(() => {
							this.editLoading = false
						})
				}
			})
		},
		cancelAddOrEdit() {
			this.editVisible = false
		},
		showEditForm(row) {
			if (row?.id) {
				this.editForm = {
					id: row.id,
					sort: row.sort,
					barrageContent: row.content
				}
			} else {
				this.editForm = {
					id: undefined,
					sort: undefined,
					barrageContent: undefined
				}
			}
			this.editVisible = true
		},
		showConfirmTips(status) {
			const action = new Map([
				[0, this.$t('common.disabled')],
				[1, this.$t('common.start_up')],
				[10, this.$t('common.delete')]
			]).get(status)
			return new Promise((resolve, reject) => {
				this.$confirm(
					`<strong>${this.$t('dxn.service_manager.action_tips', {
						action: action
					})}?</strong><br>
				<span style='color:#ababab'>${this.$t(
					'system.staff_manage.delete_account_notice'
				)}</span>`,
					this.$t('common.success_tip'),
					{
						dangerouslyUseHTMLString: true,
						confirmButtonText: this.$t('common.confirm'),
						cancelButtonText: this.$t('common.cancel'),
						type: 'warning'
					}
				)
					.then(() => {
						resolve()
					})
					.catch(() => {
						reject()
					})
			})
		},
		updateRowStatus(row, status) {
			this.showConfirmTips(status).then(() => {
				const params = { id: row.id, state: status }
				this.$api
					.updateChatPhrasesBend(params)
					.then((res) => {
						if (res?.code === 200) {
							this.$message.success(
								this.$t('common.action_success')
							)
						}
						this.loadData()
					})
					.catch(() => {})
			})
		},
		deleteRow(row) {
			this.showConfirmTips(10).then(() => {
				const params = { id: row.id, state: 2 }
				this.$api
					.updateChatPhrasesBend(params)
					.then((res) => {
						if (res?.code === 200) {
							this.$message.success(
								this.$t('common.delete_success')
							)
						} else {
							this.$message.error(this.$t('common.delete_fail'))
						}
						this.loadData()
					})
					.catch(() => {})
			})
		},
		handleConfigEdit(val) {
			this.isEdit = true
		},
		handleConfigCancel() {
			this.isEdit = false
			this.ruleForm = {
				sendMessageInterval: this.configItem.sendMessageInterval
			}
		},
		handleConfigSubmit() {
			if (!this.configData.configId) {
				this.$message.error(
					this.$t('dxn.service_manager.config_not_exist_tips')
				)
				return
			}
			if (this.ruleForm.sendMessageInterval === '') {
				this.$message.closeAll()
				this.$message.error(
					this.$t('dxn.service_manager.send_message_interval_tips')
				)
				return
			}
			const valArr = [
				'sendMessageInterval' + '_' + this.ruleForm.sendMessageInterval
			]
			const params = {
				id: this.configData.configId,
				vals: valArr.join(',')
			}
			this.btnLoading = true
			this.$api
				.updateValueAddedConfigBend(params)
				.then((res) => {
					this.btnLoading = false
					this.isEdit = false
					if (res?.code === 200) {
						this.$message.success(this.$t('common.action_success'))
					}
				})
				.catch(() => {
					this.btnLoading = false
				})
		},
		handleBarrageContentInput(val) {
			const { newStr } = getNewSubStrAndLen(val, 40)
			this.editForm.barrageContent = newStr
		}
	}
}
</script>

<style lang="scss" scoped>
.rule-form {
	margin: 15px 30px;
	.status-lable {
		line-height: 1.2;
	}
}
.show-add-btn {
	width: 100%;
	text-align: right;
	margin-bottom: 5px;
}

.disable-color {
	color: #aaaaaa;
}
.show-action-btn {
	span {
		margin-left: 15px;
		font-size: 15px;
		cursor: pointer;
	}
	.text-disable {
		color: #f6ac4a;
	}
	.text-start-up {
		color: #4f7c07;
	}
	.text-delete {
		color: #a40417;
	}
	.text-edit {
		color: #6868d9;
	}
}
</style>
